package com.pactera.madp.cp.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.cp.api.dto.greeting.GreetingDto;
import com.pactera.madp.cp.api.dto.greeting.GreetingPageDTO;
import com.pactera.madp.cp.api.em.businesslog.EventEnum;
import com.pactera.madp.cp.api.em.greeting.RangeTypeEnum;
import com.pactera.madp.cp.api.em.medium.TypeEnum;
import com.pactera.madp.cp.api.em.permission.ReqPerEnum;
import com.pactera.madp.cp.api.entity.BaseEntity;
import com.pactera.madp.cp.api.entity.BusinessLogEntity;
import com.pactera.madp.cp.api.entity.CorpEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.greeting.GreetingEntity;
import com.pactera.madp.cp.api.entity.medium.MediumEnyity;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.WorkEmployeeGreetingVO;
import com.pactera.madp.cp.api.vo.greeting.GreetingPageVO;
import com.pactera.madp.cp.common.config.FileUploadConfig;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.greeting.GreetingMapper;
import com.pactera.madp.cp.mapper.medium.MediumMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @description:好友欢迎语
 * @author: Huayu
 * @time: 2021/2/1 15:14
 */
@Service
@Slf4j
public class GreetingServiceImpl extends ServiceImpl<GreetingMapper, GreetingEntity> implements IGreetingService {

    @Autowired
    private IWorkEmployeeService workEmployeeServiceServiceImpl;
    @Autowired
    private IBusinessLogService businessLogServiceImpl;
    @Resource
    private MediumMapper mediumMapper;
    @Autowired
    private IMediumService mediumServiceImpl;
    @Autowired
    private IWorkEmployeeService workEmployeeServiceImpl;
    @Autowired
    private IWorkEmployeeDepartmentService employeeDepartmentService;
    @Autowired
    private IBusinessLogService businessLogService;
    @Autowired
    private FileUploadConfig fileUploadConfig;
    @Autowired
    private ICorpService corpService;

    @Override
    public Page<List<GreetingPageVO>> handle(Page page, GreetingPageDTO dto) {
        //处理请求参数
        return handleParams(page,dto);
    }

    @Override
    public Map<String,Object> getGreeting(String userId) {
        //查询客户跟进人信息[企业通讯录]
        WorkEmployeeEntity workEmployeeEntity = workEmployeeServiceImpl.getWorkEmployeeByWxUserId(userId, "id,corp_id");
        //查询员工欢迎语
        List<GreetingEntity> greetingEntityList = getGreetingsByCorpId(workEmployeeEntity.getCorpId(), "id,medium_id,words,range_type,employees,dept_ids");


        Map<String,Object> commonMap = new HashMap();;
        Map<String,Object> contentMap = new HashMap();
        Map<String,Object> contentMapOuter =new HashMap();
        for (GreetingEntity greetingEntity:greetingEntityList) {
            String deptIds = null;
            String[] deptArr = null;
            AtomicInteger count = new AtomicInteger();
            //检索通用欢迎语
            if(greetingEntity.getRangeType().equals(RangeTypeEnum.ALL.getCode())){
                commonMap.put("text",greetingEntity.getWords());
                commonMap.put("mediumId",greetingEntity.getMediumId());
            }
            //检索指定部门欢迎语
            log.info("greetingEntity:{}",greetingEntity);
            if(JSONObject.parseArray(greetingEntity.getDeptIds()).size() > 0){
                JSONArray jsonArray = JSONObject.parseArray(greetingEntity.getDeptIds());
                if(jsonArray.size() != 0){
                    for (Object json:
                            jsonArray) {
                        deptIds = json.toString() + ",";
                    }
                }
                deptIds = deptIds.substring(0,deptIds.length() - 1);
                deptArr = deptIds.split(",");
            }
            if(deptIds != null){
                List<Integer> deptCollect = Arrays.stream(deptArr).map(d->{return Integer.valueOf(d);}).distinct().collect(Collectors.toList());
                log.info("deptCollect:{}",deptCollect);
                List<Integer> employeeIds = workEmployeeServiceImpl.getEmployeeIdsByDeptIds(deptCollect);
                log.info("employeeIds:{}",employeeIds);
                if (employeeIds.contains(workEmployeeEntity.getId())){
                    count.set(-1);
                }
            }
            if(deptArr == null || count.get() != -1){
                continue;
            }
            contentMap.put("text",greetingEntity.getWords());
            contentMap.put("mediumId",greetingEntity.getMediumId());
            contentMapOuter.put("content",contentMap);
        }
        if (contentMapOuter.size()  == 0 && commonMap.size() > 0) {
           contentMapOuter.put("content",commonMap);
        }
        if (contentMapOuter.get("content") == null){
            return contentMapOuter;
        }
        if(!((Map<String, Object>) contentMapOuter.get("content")).get("mediumId").equals("")){
            log.info("");
            Map<String, Map<String, Object>> mediumMap = getMediumData((Integer)((Map<String, Object>)contentMapOuter.get("content")).get("mediumId"));
            HashMap<String, Object> map = new HashMap<>();
            map.put("text",((Map<String, Object>)contentMapOuter.get("content")).get("text"));
            map.put("medium",mediumMap.get("medium"));
            contentMapOuter.put("content",map);
        }
        return contentMapOuter;
    }

    @Override
    public boolean saveGreeting(GreetingDto greeting) {
        //判断用户绑定企业信息
        if (CorpContextHolder.getCorpId() == null) {
            throw new CheckedException("未选择登录企业，不可操作");
        }
        //欢迎语类型
        String typeStr = greeting.getType();
        if (typeStr.length() == 1) {
            typeStr = "-" + typeStr + "-";
        } else {
            String[] typeArr = typeStr.split(",");
            StringBuilder sb = new StringBuilder();
            for (String arr :
                    typeArr) {
                arr = "-" + arr;
                sb.append(arr);
            }
            typeStr = sb.toString() + "-";
        }
        GreetingEntity greetingEntity = new GreetingEntity();
        JSONArray jsonArray = new JSONArray();
        String employees = greeting.getEmployees();
        if(employees != null && !employees.equals("")){
            jsonArray.add(employees);
            employees = jsonArray.toJSONString();
            greetingEntity.setEmployees(employees);
        }else{
            greetingEntity.setEmployees(jsonArray.toJSONString());
        }
        JSONArray jsonArray2 = new JSONArray();
        String deptIds = greeting.getDeptIds();
        if(deptIds != null && !deptIds.equals("")){
            jsonArray2.add(deptIds);
            deptIds = jsonArray2.toJSONString();
            greetingEntity.setDeptIds(deptIds);
        }else{
            greetingEntity.setDeptIds(jsonArray2.toJSONString());
        }
        greetingEntity.setType(typeStr);
        greetingEntity.setCorpId(CorpContextHolder.getCorpId());
        greetingEntity.setCreateTime(LocalDateTime.now());
        greetingEntity.setWords(greeting.getWords());
        greetingEntity.setMediumId(greeting.getMediumId());
        greetingEntity.setRangeType(greeting.getRangeType());
        Integer integer = createGreeting(greetingEntity);
        //记录业务日志
        businessLogServiceImpl.createBusinessLog(
                greetingEntity.getGreetingId(),
                JSON.toJSONString(greetingEntity),
                EventEnum.GREETING_CREATE
        );
       return integer == 1 ;
    }

    @Override
    public boolean updateGreeting(GreetingDto greeting) {
        if (greeting.getGreetingId() == null) {
           throw new CheckedException("欢迎语ID不能为空");
        }
        if (greeting.getRangeType() == null) {
            throw new CheckedException("适用成员类型不能为空");
        }
        //欢迎语类型
        String typeStr = greeting.getType();
        if (typeStr == null || "".equals(typeStr)) {
            throw new CheckedException("欢迎语类型不能为空");
        }
        String[] typeArr = typeStr.split(",");
        StringBuilder sb = new StringBuilder();
        for (String arr :
                typeArr) {
            arr = "-" + arr;
            sb.append(arr);
        }
        typeStr = sb.toString() + "-";
        //适用成员
        String employees = greeting.getEmployees();
        if (employees != null && !"".equals(employees)) {
            String[]  employeesAttr = employees.split(",");
            StringBuilder sb1 = new StringBuilder();
            for (String string:
                    employeesAttr) {
                sb1.append(string).append(",");
            }
            employees = sb1.substring(0,sb1.length()-1);
        }
        GreetingEntity greetingEntity = new GreetingEntity();
        BeanUtils.copyProperties(greeting, greetingEntity);
        greetingEntity.setEmployees(employees);
        greetingEntity.setType(typeStr);
        //适用部门
        JSONArray jsonArray2 = new JSONArray();
        String deptIds = greeting.getDeptIds();
        if(deptIds != null && !deptIds.equals("")){
            jsonArray2.add(deptIds);
            deptIds = jsonArray2.toJSONString();
            greetingEntity.setDeptIds(deptIds);
        }else{
            greetingEntity.setDeptIds(jsonArray2.toJSONString());
        }

        //创建数据
        Integer i = updateGreetingById(greetingEntity);
        if (i < 1) {
            throw new CheckedException("系统错误,欢迎语更新失败");
        }

        //记录业务日志
        boolean result = businessLogServiceImpl.createBusinessLog(
                Integer.valueOf(greetingEntity.getGreetingId().toString()),
                JSON.toJSONString(greetingEntity),
                EventEnum.GREETING_UPDATE
        );

        if (!result) {
            throw new CheckedException("系统错误,欢迎语更新失败");
        }
        return i==1;
    }


    /**
     *
     *
     * @description: 发送欢迎语
     * @author: Huayu
     * @time: 2021/3/30 18:36
     */
    @Override
    public void applyWxSendContactMessage(String wxCorpId, String welcomeCode, Map<String, JSONObject> contactInfo, Map<String, Object> content) {
        CorpEntity corps = corpService.getOne(Wrappers.<CorpEntity>lambdaQuery().eq(CorpEntity::getWxCorpId,wxCorpId));
        Map<String,Object> sendWelcomeDataMap = new HashMap();
        Map<String,Object> sendWelcomeTextDataMap = new HashMap();
        //微信消息体 - 文本
        if(content.get("text") != null){
            String contentStr = content.get("text").toString();
            String name = null;
            for (Map.Entry<String, JSONObject> mapEntry : contactInfo.entrySet()) {
                JSONObject json = mapEntry.getValue();
                if (json.getInteger("errcode") == 0) {
                    JSONObject contactJson = json.getJSONObject("external_contact");
                    name = contactJson.getString("name");
                }
            }
            log.info("name:"+name);
            contentStr = contentStr.replaceAll("##用户名称##",name);
            HashMap<String, String> map = new HashMap<>();
            map.put("content", contentStr);
            sendWelcomeTextDataMap.put("text",map);
        }
        //微信消息体 - 媒体文件
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info("content为 : "+content);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        if(content.get("medium") != null){
            Integer type = (Integer)(((Map<String,Object>)content.get("medium")).get("mediumType"));
            log.info("type为："+type);
            switch (type){
                case  2:
                    Map<String, Object> hashMap = new HashMap<>();
                    Map<String, Object> map = (Map<String, Object>) content.get("medium");
                    log.info("map:"+map);
                    List o = (List)map.get("mediumContent");
                    log.info("o:"+o);
                    cn.hutool.json.JSONObject parseObj = JSONUtil.parseObj(o.get(0));
//                    JSONObject jsonObject = JSONObject.parseObject(o.toString());
                    log.info("jsonObject:"+parseObj);
                    String jsonObjectString = parseObj.getStr("content");
                    log.info("jsonObjectString:"+jsonObjectString);
                    cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(jsonObjectString);
//                    JSONObject object = JSONObject.parseObject(jsonObjectString);
                    log.info("object:"+jsonObject);
                    String imagePath = jsonObject.getStr("url");
                    imagePath = imagePath == null ? "" : imagePath;
//                    String jsonStr = (String)((Map<String, Object>) content.get("medium")).get("mediumContent");
//                    log.info("jsonStr为:"+jsonStr);
//                    String imagePath = JSONObject.parseObject(JSON.parseObject(jsonObject).getString("content")).getString("url");
                    log.info("imagePath为："+imagePath);
                    /*String[] split = imagePath.split("/");
                    String fileUrl = fileUploadConfig.getRealPath() + File.separator + split[split.length-1];*/
                    String fileUrl = fileUploadConfig.getRealPath() + imagePath.replace(fileUploadConfig.getAccessPath(),"");
                    File file = new File(fileUrl);
                    log.info("开始上传临时素材");

                    log.info("corpId:"+corps.getCorpId());
                    String mediaId = WxApiUtils.uploadImageToTemp(corps.getCorpId(), file);
                    log.info("mediaId:"+mediaId);
                    hashMap.put("media_id", mediaId);
                    sendWelcomeDataMap.put("image",hashMap);
                    sendWelcomeDataMap.put("msgtype","image");
                    log.info("hashMap："+hashMap);
                    log.info("sendWelcomeDataMap1"+sendWelcomeDataMap);
                    break;
                case 3:
                    Map<String,Object> linkMap = new HashMap();
                    Map<String, Object> map1 = (Map<String, Object>) content.get("medium");
                    log.info("map:"+map1);
                    List o1 = (List) map1.get("mediumContent");
                    log.info("o:"+o1);
                    cn.hutool.json.JSONObject parseObj1 = JSONUtil.parseObj(o1.get(0));
//                    JSONObject jsonObject = JSONObject.parseObject(o.toString());
                    log.info("jsonObject:"+parseObj1);
                    String jsonObjectString1 = parseObj1.getStr("content");
                    log.info("jsonObjectString:"+jsonObjectString1);
                    cn.hutool.json.JSONObject jsonObject1 = JSONUtil.parseObj(jsonObjectString1);
//                    JSONObject object = JSONObject.parseObject(jsonObjectString);
                    log.info("object:"+jsonObject1);
//                    String jsonLink = (String)((Map<String, Object>) content.get("medium")).get("mediumContent");
//                    JSONObject parseObject = JSONObject.parseObject(JSON.parseObject(jsonLink).getString("content"));
                    log.info("parseObject："+jsonObject1);
                    linkMap.put("title",jsonObject1.get("title"));
                    String imgUrl = jsonObject1.get("imgUrl").toString();
                    //自定义图片url处理
                    linkMap.put("picurl",imgUrl.startsWith("/mfs/medium/corp-") ? fileUploadConfig.getServerUrl() + imgUrl : imgUrl);
                    linkMap.put("desc",jsonObject1.get("description"));
                    linkMap.put("url",jsonObject1.get("link"));
                    sendWelcomeDataMap.put("msgtype","link");
                    sendWelcomeDataMap.put("link",linkMap);

                    log.info("sendWelcomeDataMap2"+sendWelcomeDataMap);
                    break;
                case 6:
                    Map<String,Object> miniMap = new HashMap();
//                    String jsonLinks = (String)((Map<String, Object>) content.get("medium")).get("mediumContent");
//                    JSONObject jsonMiniObject = JSONObject.parseObject(JSON.parseObject(jsonLinks).getString("content"));
                    Map<String, Object> map2 = (Map<String, Object>) content.get("medium");
                    log.info("map:"+map2);
                    List o2 = (List) map2.get("mediumContent");
                    log.info("o:"+o2);
                    cn.hutool.json.JSONObject parseObj2 = JSONUtil.parseObj(o2.get(0));
//                    JSONObject jsonObject = JSONObject.parseObject(o.toString());
                    log.info("jsonObject:"+parseObj2);
                    String jsonObjectString2 = parseObj2.getStr("content");
                    log.info("jsonObjectString:"+jsonObjectString2);
                    cn.hutool.json.JSONObject jsonObject2 = JSONUtil.parseObj(jsonObjectString2);
//                    JSONObject object = JSONObject.parseObject(jsonObjectString);
                    log.info("object:"+jsonObject2);
                    log.info("jsonMiniObject为:"+jsonObject2);
                    String imagePathMini = jsonObject2.getStr("imgUrl");
                    imagePathMini = imagePathMini == null ? "" : imagePathMini;
                    /*String[] splits = imagePathMini.split("/");
                    String fileUrls = fileUploadConfig.getRealPath() + File.separator + splits[splits.length-1];*/
                    String fileUrls = fileUploadConfig.getRealPath() + imagePathMini.replace(fileUploadConfig.getAccessPath(),"");
                    File imageFileMini = new File(fileUrls);
                    String mediaIdMini = WxApiUtils.uploadImageToTemp(corps.getCorpId(), imageFileMini);
                    miniMap.put("title",jsonObject2.getStr("title"));
                    miniMap.put("pic_media_id",mediaIdMini);
                    miniMap.put("appid",jsonObject2.getStr("appid"));
                    miniMap.put("page",jsonObject2.getStr("page"));
                    sendWelcomeDataMap.put("msgtype","miniprogram");
                    sendWelcomeDataMap.put("miniprogram",miniMap);

                    log.info("sendWelcomeDataMap3"+sendWelcomeDataMap);
            }
        }
        log.info("sendWelcomeDataMap"+sendWelcomeDataMap);
        //发送欢迎语
        String respStr = WxApiUtils.sendWelcomeCode(corps.getCorpId(),sendWelcomeDataMap,sendWelcomeTextDataMap,welcomeCode);
        if(respStr == null){
            System.out.println("请求微信上推送新增客户信息失败>>>>>>>");
        }
    }

    private Map<String,Map<String,Object>> getMediumData(Integer mediumId) {
        Map<String,Object> map = null;
        Map<String,Map<String,Object>> mapData = new HashMap();
        MediumEnyity mediumEntity= mediumServiceImpl.getOne(Wrappers.<MediumEnyity>lambdaQuery().eq(MediumEnyity::getId,mediumId));
        if(mediumEntity != null){
            map = new HashMap();
            map.put("mediumType",mediumEntity.getType());
            map.put("mediumContent", JSONUtil.parseArray(mediumEntity.getContent()));
        }
        mapData.put("medium",map);
        return mapData;
    }

    /**
     * @author: yangpengwei
     * @time: 2021/3/17 11:19 上午
     * @description 权限管理查询条件配置
     */
    private void setWrapperPermission(LambdaQueryChainWrapper<GreetingEntity> wrapper, ReqPerEnum permission) {
        if (permission == ReqPerEnum.ALL) {
            return;
        }

        LambdaQueryChainWrapper<BusinessLogEntity> logWrapper = businessLogService.lambdaQuery();
        if (permission == ReqPerEnum.DEPARTMENT) {
            // 查询员工所属的部门 id 列表
            List<Integer> idList = employeeDepartmentService.getDeptAndChildDeptEmpIdList();
            logWrapper.in(BusinessLogEntity::getOperationId, idList);
        }

        if (permission == ReqPerEnum.EMPLOYEE) {
            int empId = AccountService.getEmpId();
            logWrapper.eq(BusinessLogEntity::getOperationId, empId);
        }

        // 渠道码业务 id 列表 (渠道码 id 列表)
        List<Integer> idList = logWrapper.in(
                BusinessLogEntity::getEvent,
                Arrays.asList(EventEnum.CHANNEL_CODE_CREATE.getCode(), EventEnum.CHANNEL_CODE_UPDATE.getCode())
        ).list().stream().map(BusinessLogEntity::getBusinessId).collect(Collectors.toList());

        if (idList.isEmpty()) {
            wrapper.eq(GreetingEntity::getGreetingId, -1);
        } else {
            wrapper.in(GreetingEntity::getGreetingId, idList);
        }
    }


    /**
     *
     *
     * @description:创建欢迎语
     * @author: Huayu
     * @time: 2021/2/2 16:27
     */
    @Override
    public Integer createGreeting(GreetingEntity greetingEntity) {
        return this.baseMapper.insert(greetingEntity);
    }


    /**
     *
     *
     * @description:更新欢迎语
     * @author: Huayu
     * @time: 2021/2/3 15:30
     */
    @Override
    public Integer updateGreetingById(GreetingEntity greetingEntity) {
        UpdateWrapper<GreetingEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",greetingEntity.getGreetingId());
        updateWrapper.set("range_type",greetingEntity.getRangeType());
        JSONArray jsonArray = new JSONArray();
        String employees = greetingEntity.getEmployees();
//        if(employees != null && !employees.equals("")){
//            String[]  employeesArr = employees.split(",");
//            for (String employee:
//            employeesArr) {
//                jsonArray.add(employee);
//            }
//            employees = jsonArray.toJSONString();
//            updateWrapper.set("employees",employees);
//        }

        if(employees != null && !employees.equals("")){
            jsonArray.add(employees);
            employees = jsonArray.toJSONString();
            greetingEntity.setEmployees(employees);
        }else{
            greetingEntity.setEmployees(jsonArray.toJSONString());
        }
        updateWrapper.set("type",greetingEntity.getType());
        updateWrapper.set("words",greetingEntity.getWords());
        updateWrapper.set("medium_id",greetingEntity.getMediumId() == null ? 0 :greetingEntity.getMediumId());
        updateWrapper.set("corp_id", CorpContextHolder.getCorpId());
        greetingEntity.setCorpId(CorpContextHolder.getCorpId());
        greetingEntity.setUpdateTime(LocalDateTime.now());
        Integer i = this.baseMapper.update(greetingEntity,updateWrapper);
        return i;
    }


    /**
     * @description:获取欢迎语信息
     * @author: Huayu
     * @time: 2021/2/3 16:10
     */
    @Override
    public GreetingEntity getGreetingById(Integer greetingId,String clStr) {
        QueryWrapper<GreetingEntity> greetingEntityQueryWrapper = new QueryWrapper();
        if(clStr == null){
            greetingEntityQueryWrapper.getSqlSelect();
        }else{
            greetingEntityQueryWrapper.select(clStr);
        }
        greetingEntityQueryWrapper.eq("id",greetingId);
        return this.baseMapper.selectOne(greetingEntityQueryWrapper);
    }

    /**
     * @description:删除欢迎语
     * @author: Huayu
     * @time: 2021/2/3 16:21
     */
    @Override
    public boolean deleteGreeting(Integer greetingId) {
        return this.baseMapper.deleteById(greetingId) == 1;
    }

    @Override
    public List<GreetingEntity> getGreetingsByCorpId(Integer corpId, String s) {
        QueryWrapper<GreetingEntity> greetingEntityQueryWrapper = new QueryWrapper();
        greetingEntityQueryWrapper.select(s);
        greetingEntityQueryWrapper.eq("corp_id",corpId);
        return this.baseMapper.selectList(greetingEntityQueryWrapper);
    }

    @Override
    public GreetingPageVO getGreetingById(Integer id) {
        //获取欢迎语详情
        GreetingEntity greetingEntity = getGreetingById(id,null);
        if(greetingEntity == null){
            throw new CheckedException("此欢迎语不存在,不可操作");
        }
        GreetingPageVO pageVO = new GreetingPageVO();
        if (greetingEntity.getMediumId() != 0){
            MediumEnyity medium = mediumServiceImpl.getById(greetingEntity.getMediumId());
            pageVO.setMediumContent(JSONUtil.parseArray(medium.getContent()));
        }
        pageVO.setGreetingId(greetingEntity.getGreetingId());
        //欢迎语类型
        String typeTextArr = greetingEntity.getType();
        //typeTextArr = typeTextArr.substring(0,typeTextArr.length()-1);
        String[] typeTextList = StringUtils.split(typeTextArr,"-");
        String  typeText = TypeEnum.getTypeByCode(Integer.valueOf(typeTextList[0]));
        Integer  type = Integer.valueOf(typeTextList[0]);
        pageVO.setTypeText(typeText);
        pageVO.setType(type);
        pageVO.setRangeType(greetingEntity.getRangeType());
        pageVO.setRangeTypeText(RangeTypeEnum.getTypeByCode(greetingEntity.getRangeType()));
        pageVO.setEmployees(getEmployees(greetingEntity.getRangeType(),greetingEntity.getEmployees()));
        pageVO.setMediumId(greetingEntity.getMediumId());

        pageVO.setWords(greetingEntity.getWords());
        pageVO.setCreateTime(greetingEntity.getCreateTime());
        return pageVO;
    }

    private Object getEmployees(String employees) {
        JSONArray jsonArray = JSONObject.parseArray(employees);
        if(jsonArray.size() != 0){
            for (Object json:
                    jsonArray) {
                employees = json.toString() + ",";
            }
        }
        employees = employees.substring(0,employees.length() - 1);
        List<WorkEmployeeEntity> workEmployeeEntityList = workEmployeeServiceServiceImpl.getWorkEmployeesById(employees);
        List<Map<String, Object>> workEmployeeNewEntityList = new ArrayList<>();
        if (workEmployeeEntityList.size() > 0) {
            for (WorkEmployeeEntity workEmployeeEntity :
                    workEmployeeEntityList) {
                Map<String, Object> map = new HashMap<>();
                map.put("employeeId", workEmployeeEntity.getId());
                map.put("employeeName", workEmployeeEntity.getName());
                workEmployeeNewEntityList.add(map);
            }
            return workEmployeeNewEntityList;
        } else {
            return workEmployeeNewEntityList;
        }
    }

    private Page<List<GreetingPageVO>> handleParams(Page page, GreetingPageDTO dto) {
        // 列表查询条件
        Integer corpId = CorpContextHolder.getCorpId();
        // 查询数据
        LambdaQueryChainWrapper<GreetingEntity> wrapper = lambdaQuery();
        // 权限管理数据权限
        setWrapperPermission(wrapper, dto.getPermission());

//        Page<GreetingEntity> page = ApiRespUtils.initPage(req);
        wrapper.orderByDesc(GreetingEntity ::getCreateTime);
        if (dto.getType() != null){
            wrapper.eq(GreetingEntity::getType,"-"+dto.getType()+"-");
        }
        if (!StringUtils.isBlank(dto.getSearch())){
            wrapper.like(GreetingEntity::getWords,dto.getSearch());
        }
        if (dto.getStartTime() != null && dto.getEndTime() != null && !dto.getEndTime().equals("") && !dto.getStartTime().equals("")){
            wrapper.gt(BaseEntity::getCreateTime,dto.getStartTime()+" 00:00:00");
            wrapper.lt(BaseEntity::getCreateTime,dto.getEndTime()+ " 23:59:59");
        }
        wrapper.eq(GreetingEntity::getCorpId, CorpContextHolder.getCorpId());
        wrapper.page(page);

        List<GreetingPageVO> greetingPageVOS = new LinkedList<>();
        Map<String, Object> mapData = new HashMap<String, Object>();
//        mapData.put("page", new PageModel(req.getPerPage(), (int) page.getTotal(), (int) page.getSize()));
        //查询已存在的数据
        mapData = hadGreetings(page.getRecords(), mapData);
        //欢迎语素材handle
        List<GreetingEntity> greetingEntityList = page.getRecords();
        Integer mediumId = null;
        String mediumContent = "";
        for (GreetingEntity greetingEntity : greetingEntityList) {
            GreetingPageVO pageVO = new GreetingPageVO();
            mediumId = greetingEntity.getMediumId();
            if (mediumId != 0){
                MediumEnyity medium = getMedium(mediumId);
                pageVO.setMediumContent(JSONUtil.parseArray(medium.getContent()));
            }

            //欢迎语类型
            String typeTextArr = greetingEntity.getType();
            String[] typeTextList = StringUtils.split(typeTextArr,"-");
            String typeText = null;
            Integer type = null;

            typeText = TypeEnum.getTypeByCode(Integer.valueOf(typeTextList[0]));
            type = Integer.valueOf(typeTextList[0]);

            String s = greetingEntity.getDeptIds().replaceAll("\\[", "").replaceAll("\\]", "");
            String all = s.replaceAll("\"", "").replaceAll("\"", "");
            String[] split = all.split(",");
            List<Integer> deptCollect = all.equals("") ? new ArrayList<Integer>() : Arrays.stream(split).map(d->{return Integer.valueOf(d);}).distinct().collect(Collectors.toList());

            pageVO.setGreetingId(greetingEntity.getGreetingId());
            pageVO.setTypeText(typeText);
            pageVO.setType(type);
            pageVO.setRangeType(greetingEntity.getRangeType());
            pageVO.setRangeTypeText(RangeTypeEnum.getTypeByCode(greetingEntity.getRangeType()));
            pageVO.setEmployees(getEmployees(greetingEntity.getRangeType(), greetingEntity.getEmployees()));
            pageVO.setDeptIds(deptCollect);
            pageVO.setMediumId(greetingEntity.getMediumId());

            pageVO.setWords(greetingEntity.getWords());
            pageVO.setCreateTime(greetingEntity.getCreateTime());
            greetingPageVOS.add(pageVO);
        }

        SubPage subPage = new SubPage();
        subPage.setRecords(greetingPageVOS);
        subPage.setCurrent(page.getCurrent());
        subPage.setSize(page.getSize());
        subPage.setTotal(page.getTotal());
        subPage.setExtraProps(mapData);
        return subPage;
    }

    private List<WorkEmployeeGreetingVO> getEmployees(Integer rangeType, String employees) {
        if(rangeType.equals(1)){
            String msg = RangeTypeEnum.getTypeByCode(rangeType);
            LinkedList<WorkEmployeeGreetingVO> greetingVOS = new LinkedList<>();
            WorkEmployeeGreetingVO greetingVO = new WorkEmployeeGreetingVO();
            greetingVO.setName(msg);
            greetingVOS.add(greetingVO);
            return greetingVOS;
        }else{
            JSONArray jsonArray = JSONObject.parseArray(employees);
            if(jsonArray.size() != 0){
                for (Object json:
                        jsonArray) {
                    employees = json.toString() + ",";
                }
            }
            employees = employees.substring(0,employees.length() - 1);
            List<WorkEmployeeEntity> workEmployeeEntityList = workEmployeeServiceImpl.getWorkEmployeesById(employees);
            List<WorkEmployeeGreetingVO> greetingVOS = new LinkedList<>();
            for (WorkEmployeeEntity workEmployeeEntity :
                    workEmployeeEntityList) {
//                if (workEmployeeEntity != null) {
//                    name = workEmployeeEntity.getName();
//                    name = name + ",";
//                }
                WorkEmployeeGreetingVO greetingVO = new WorkEmployeeGreetingVO();
                BeanUtils.copyProperties(workEmployeeEntity,greetingVO);
                greetingVOS.add(greetingVO);
            }
//            name = name.substring(0, name.length() - 1);
//            listStr.add(name);
            return greetingVOS;
        }
    }

    private MediumEnyity getMedium(Integer mediumId) {
        QueryWrapper<MediumEnyity> mediumQueryWrapper = new QueryWrapper();
        mediumQueryWrapper.select("id", "type", "content");
        mediumQueryWrapper.eq("id",mediumId);
        return this.mediumMapper.selectOne(mediumQueryWrapper);
    }

    private Map<String, Object> hadGreetings(List<GreetingEntity> greetingEntityList, Map<String, Object> mapData) {
        Integer flag = 0;
        if (greetingEntityList != null || greetingEntityList.size() != 0) {
            String employeesArr = null;
            for (GreetingEntity greetingEntity :
                    greetingEntityList) {
                if (greetingEntity.getRangeType().equals(RangeTypeEnum.ALL.getCode())) {
                    flag = 1;
                }
                employeesArr = greetingEntity.getEmployees();
                JSONArray jsonArray = JSONObject.parseArray(employeesArr);
                if(jsonArray.size() != 0){
                    for (Object json:
                    jsonArray) {
                        employeesArr = json.toString() + ",";
                    }
                }
            }
            if (flag.equals(1)) {
                mapData.put("hadGeneral", 1);
            } else {
                mapData.put("hadGeneral", 0);
            }
           if(employeesArr != null && employeesArr.length() > 0){
                employeesArr = employeesArr.substring(0,employeesArr.length() - 1);
                mapData.put("hadEmployees",employeesArr.split(","));
           }else{
                mapData.put("hadEmployees", JSONObject.parseArray(employeesArr));
           }
        }
        return  mapData;
    }
}
